// pages/orderPut/orderPut.js
var app     = getApp();//获取全局注册函数
var utils = require('../../utils/util.js');
var base64Js = require('../../utils/base64.js');
var md5Js = require('../../utils/md5.js');
var utf8  = require('../../utils/utf8.js');
var controller = {};
controller.onLoad = function(options){
  // 页面初始化 options为页面跳转所带来的参数
};
controller.onReady = function(){
  //页面加载完成触发
  try{
    var order_items  = wx.getStorageSync('order_info');
    console.log(order_items.order_info);
    var payoffline = order_items.order_info.payTypeList["1"].items;
    for (var i = 0; i < payoffline.length;i++){
      if (payoffline[i]['is_checked']==1){
        var payofflineid = payoffline[i]['id'];
        var account = payoffline[i]['account'];
        var bank_name = payoffline[i]['bank_name'];
        var bank_number = payoffline[i]['bank_number'];
      }
    }
    var payonline = order_items.order_info.payTypeList["0"].items;
    for (var i = 0; i < payonline.length; i++) {
      if (payonline[i]['is_checked'] == 1) {
        var payonlineid = payonline[i]['id'];
      }
    }
    if (order_items.order_info.payTypeList["0"]["is_checked"] == 1 ){
      var pay_type_item_id = payonlineid;
    }else{
      var pay_type_item_id = payofflineid;
    }
    if(order_items){
      this.setData({
        order_items:order_items.order_info,
        pay_type_item_id: pay_type_item_id,
        delivery_time: order_items.order_info.dataList[0],
        pay_type_status: order_items.order_info.payTypeList["0"]["is_checked"],
        payonlineid: payonlineid,
        payofflineid: payofflineid,
        account: account,
        bank_name: bank_name,
        bank_number: bank_number,
        });
    }
  }catch(e){
    wx.showModal({
      title:'提示',
      content:'订单信息获取失败',
      showCancel:false,
      confirmColor:'black'
    })
    console.log('订单信息获取失败');    
  }
};

//修改配送时间
controller.deliverytimeChange = function (e) {
  var delivery_time = e.detail.value;
  this.setData({
    delivery_time: delivery_time
  })
}

//点击支付类型获取数据
controller.payChange = function(e){
    var pay_type = e.detail.value;
    console.log(pay_type);
    var order_items  = wx.getStorageSync('order_info');
    var payTypeList = order_items.order_info.payTypeList;
    var payoffline = order_items.order_info.payTypeList["1"].items;
    for (var i = 0; i < payoffline.length; i++) {
      if (payoffline[i]['is_checked'] == 1) {
        var payofflineid = payoffline[i]['id'];
        var account = payoffline[i]['account'];
        var bank_name = payoffline[i]['bank_name'];
        var bank_number = payoffline[i]['bank_number'];
      }
    }
    var payonline = order_items.order_info.payTypeList["0"].items;
    for (var i = 0; i < payonline.length; i++) {
      if (payonline[i]['is_checked'] == 1) {
        var payonlineid = payonline[i]['id'];
      }
    }
    if (pay_type == 'online_pay'){
          pay_type = 'online_pay',
          this.setData({
            pay_type_status:1,
            pay_type:pay_type,
            payonlineid: payonlineid,
            pay_type_item_id: payonlineid,
            
          })
        }else{
          pay_type = 'offline_pay'
          this.setData({
            pay_type_status: 0,
            pay_type:pay_type,
            payonlineid: payofflineid,
            pay_type_item_id: payofflineid,
            account: account,
            bank_name: bank_name,
            bank_number: bank_number
          })
        }
}

controller.onlineChange=function(e){
  var pay_type = e.detail.value;
  this.setData({
    pay_type_item_id: pay_type,
    payonlineid:pay_type
  })
}

//选择线下支付时获取信息
controller.changeType = function(e){
    var paytypeid = e.detail.value;
    var order_items = wx.getStorageSync('order_info');
    var paytype = order_items.order_info.payTypeList["1"].items;
    var account = 'aa';
    for (var i = 0; i < paytype.length; i++) {
      if (paytype[i]['id'] == paytypeid) {
        var account = paytype[i]['account'];
        var bank_name = paytype[i]['bank_name'];
        var bank_number = paytype[i]['bank_number'];
      }
    }
    this.setData({
      pay_type_item_id:paytypeid,
      account: account,
      bank_name: bank_name,
      bank_number: bank_number,
    })
}
//提交表单
controller.formSubmit = function(e){
  try{
    var user_info  = wx.getStorageSync('user_info');
    console.log(user_info);
    var request_data = user_info.user_itmes;
    var paytype = e.detail.target.dataset.paytype;
    var delivery_time = e.detail.target.dataset.deliverytime;
    var order_items  = wx.getStorageSync('order_info');
    var payTypeList = order_items.order_info.payTypeList;
    var payTypeItemId = payTypeList["0"].items[1].id;
    var pay_type_item_id = e.detail.target.dataset.paytypeitemid;
    //判断支付方式并赋值
    if (paytype == 'online_pay'){
      var isPayType = 1,
      pay_type_item_id = payTypeItemId
    }else{
      var isPayType = 0,
      pay_type_item_id = pay_type_item_id
    }

    //判断有没有选择开户信息
    if (paytype != 'online_pay' && pay_type_item_id == undefined){
        wx.showModal({
          title: '提示',
          content: '请选择开户信息',
          showCancel:false,
          confirmColor:'black'
        })
        return false;
    }
    var uid = request_data.id.toString();
    var post_data = e.detail.value;
    var order_id  = post_data.order_id.toString();
    console.log(order_id);
    var contact = utf8.encode(post_data.contact);
    var tel      = post_data.tel;
    var address  = utf8.encode(post_data.address);
    var rmak = post_data.rmak?post_data.rmak:'';
    if((order_id)&&(contact)&&(tel)&&(address)&&(delivery_time)&&(user_info)){
      //调用接口actionType=submit将订单状态从0变为1
      var parms_url  = app.request_url+'C_Order/'+order_id+'?';
      var payload_str = 'actionType=submit';      
      var channel_id = request_data.channelId;
          payload_str += '&deliveryTime='+delivery_time;
          payload_str += '&contact='+contact;
          payload_str += '&tel='+tel;
          payload_str += '&address='+address;
          payload_str += '&remark='+rmak;
          payload_str += '&uid='+uid;
          payload_str += '&channelId='+channel_id;
          payload_str += '&isPayType='+isPayType;
          payload_str += '&pay_type_item_id='+pay_type_item_id;
      var private_key = user_info.private_key;
      var t           =  new Date().getTime().toString();
      var payload = base64Js.encode(payload_str);
          //actionType=submit&deliveryTime=2017-02-18 16:38:00&contact=客户3&tel=17701619893&address=街道女&remark=&uid=100000202&channelId=204&isPayType=1&pay_type_item_id=3
      var k = md5Js.hex_md5(private_key+order_id+t+payload);
          parms_url += 'uid='+uid;
          parms_url += '&userType='+request_data.type;
          parms_url += '&t='+t;
          parms_url += '&k='+k;
          parms_url += '&v='+app.version;
          //判断支付类型1是wx、0是线下支付
          if(isPayType == 1){
            wx.request({
              url: parms_url,
              data: {payload:payload},
              method: 'PUT', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
              header: {
                      'content-type': 'application/x-www-form-urlencoded'
              },
              success: function(res){
                if((res.statusCode=='200')&&(res.data.Success==1)){
                  //修改成功后调用支付接口actionType=prePay
                    try{
                    // var APPID = res.data.CallInfo.orderHeader.APPID
                    // var APPSECRET = res.data.CallInfo.orderHeader.APPSECRET
                    //     wx.setStorageSync('APPID', APPID);
                    //     wx.setStorageSync('APPSECRET', APPSECRET);
                    var user_info  = wx.getStorageSync('user_info');
                    var request_data = user_info.user_itmes;
                    var uid         = request_data.id.toString();
                    console.log(e);
                    var order_id  = e.detail.target.dataset.orderid;
                        wx.setStorageSync('order_id', order_id);
                    if((order_id)&&(user_info)){
                      var parms_url  = app.request_url+'C_Order/'+order_id+'?';
                      var payload_str = 'actionType=prePay';      
                      var channel_id = request_data.channelId;
                      var open_id = wx.getStorageSync('openID');
                      console.log(app);
                          payload_str += '&platform=WX';
                          payload_str += '&uid='+uid;
                          payload_str += '&channelId='+channel_id;
                          payload_str += '&enterpriseId='+request_data.enterpriseId;
                      var private_key = user_info.private_key;
                      var t           =  new Date().getTime().toString();
                      var payload = base64Js.encode(payload_str);
                      var k = md5Js.hex_md5(private_key+order_id+t+payload);
                          parms_url += 'uid='+uid;
                          parms_url += '&userType='+request_data.type;
                          parms_url += '&open_id='+open_id;
                          parms_url += '&t='+t;
                          parms_url += '&k='+k;
                          parms_url += '&v='+app.version;
                          console.log(parms_url);
                            //http://rest.test.freshqiao.com/C_Order/3632?userType=1&uid=100000202&t=1487310037394&k=1feb0145efa1b066151674df667357e7&uid=100000202&v=2
                          //https://rest.test.freshqiao.com/C_Order/3631?uid=100000202&userType=1&t=1487309854571&k=fa5cf25add545517011094ff5f09ca74&v=2
                          wx.request({
                              url: parms_url,
                              method: 'PUT',
                              data:{payload:payload},
                              header: {
                                    'content-type': 'application/x-www-form-urlencoded'
                              },
                              success: function(res){
                                var respones = res;
                                console.log(respones);
                                var outTradeNo = respones.data.CallInfo.out_trade_no
                                    wx.setStorageSync('outTradeNo', outTradeNo) 
                                var appid = respones.data.CallInfo.rsa.appId;
                                var timeStamp = respones.data.CallInfo.rsa.timeStamp;
                                var nonceStr = respones.data.CallInfo.rsa.nonceStr;
                                var packages = respones.data.CallInfo.rsa.package;
                                var paysign = respones.data.CallInfo.rsa.sign;
                                //返回的数据，再调用wx.requestPayment进行二次签名
                                if((respones.statusCode=='200')&&(respones.data.Success==1)){
                                  wx.requestPayment({
                                      'appId': appid,
                                      'timeStamp': timeStamp,
                                      'nonceStr': nonceStr,
                                      'package': packages,
                                      'signType': 'MD5',
                                      'paySign': paysign,
                                      'success':function(res){
                              //支付成功后返回res.errMsg='requestPayment:ok',说明客户已支付 调用actionType=postPay接口将订单状态修改为已经支付
                                        if(res.errMsg == 'requestPayment:ok'){
                                          try{
                                              var _this = this;
                                              //获取缓存的用户对象信息
                                              var user_info =  wx.getStorageSync('user_info');
                                              //如果用户信息不为空则请求首页接口获取产品等信息。
                                              if(user_info){
                                                var request_data = user_info.user_itmes;
                                                var uid         = request_data.id.toString();
                                                var order_id    =  wx.getStorageSync('order_id');
                                                var private_key = user_info.private_key;
                                                var outTradeNo = wx.getStorageSync('outTradeNo')
                                                var payload_str = 'actionType=postPay'; 
                                                    payload_str += '&platform=WX';
                                                    payload_str += '&uid='+uid;
                                                    payload_str += '&channelId='+channel_id;
                                                    payload_str += '&enterpriseId='+request_data.enterpriseId;
                                                    payload_str += '&outTradeNo='+wx.getStorageSync('outTradeNo')
                                                var payload = base64Js.encode(payload_str);
                                                    console.log(payload);console.log(11);
                                                var t           =  new Date().getTime().toString();
                                                var k = md5Js.hex_md5(private_key+t+payload);
                                                var parms_url   = app.request_url+'C_Order/'+order_id+'?';
                                                    parms_url += 'uid='+request_data.id;
                                                    parms_url += '&userType='+request_data.type;
                                                    parms_url += '&t='+t;
                                                    parms_url += '&k='+k;
                                                    parms_url += '&v='+app.version;
                                                //调用产品页接口
                                                wx.request({
                                                  url: parms_url,
                                                  method: 'PUT',
                                                  data:{payload:payload},
                                                  header: {
                                                        'content-type': 'application/x-www-form-urlencoded'
                                                  },
                                                  success: function(res){
                                                    var respones = res;
                                                    //请求成功分配模板变量
                                                    if((respones.statusCode=='200')&&(respones.data.Success==1)){
                                                        //分配模板变量
                                                        console.log(respones); 
                                                        wx.showToast({  
                                                          title: '支付成功',  
                                                          icon: 'success',
                                                        })
                                                        wx.setStorageSync('cart_info','');
                                                        setTimeout(function(){
                                                            wx.redirectTo({
                                                              url: '../orderlist/orderlist',
                                                            })
                                                        },2000) 
                                                    }
                                                  }
                                                })
                                              }
                                          }catch(e){
                                            console.log('error=>'+e.message);return false;
                                          }
                                        }
                                      },
                                      'fail':function(res){
                                        console.log(res);
                                        wx.showToast({
                                          title:'支付失败',
                                        });
                                      }
                                    })
                                  }
                              }
                          })   
                    }
                  }catch(e){
                    wx.showToast({
                      title:'提交失败',
                      icon:'loading',
                    });
                    console.log(e.message);return;
                  }
                }else{
                    wx.showToast({
                      title:res.data.ErrorMsg,
                      icon:'loading',
                    });
                }
              },
            })
          }else{
              wx.request({
                url: parms_url,
                method: 'PUT',
                data:{payload:payload},
                header: {
                      'content-type': 'application/x-www-form-urlencoded'
                },
                success: function(res){
                  var respones = res;
                  if((respones.statusCode=='200')&&(respones.data.Success==1)){
                        wx.redirectTo({
                            url: '../orderlist/orderlist',
                          });
                        wx.setStorageSync('cart_info', []);
                    }else{
                         wx.showToast({
                            title:respones.data.ErrorMsg,
                            icon:'loading',
                         });
                    }
                }
            })   
          }
    }
  }catch(e){
    wx.showToast({
      title:'结算失败',
      icon:'loading',
    });
    console.log(e.message);return;
  }
}

//支付方式弹窗
controller.payshow = function (e) {
  var paytypeid = e.target.dataset.paytypeid;
  var animation = wx.createAnimation({
    duration: 200,
    timingFunction: "linear",
    delay: 0
  })
  this.animation = animation
  animation.translateY(300).step()
  this.setData({
    animationData: animation.export(),
    showModalStatus2: true,
    paytypeid: paytypeid
  })
  setTimeout(function () {
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export()
    })
  }.bind(this), 200)

}
//配送时间弹窗
controller.timeshow = function (e) {
  var deliverytime = e.target.dataset.deliverytime;
  var animation = wx.createAnimation({
    duration: 200,
    timingFunction: "linear",
    delay: 0
  })
  this.animation = animation
  animation.translateY(300).step()
  this.setData({
    animationData: animation.export(),
    deliverytime:deliverytime,
    showModalStatus1: true
  })
  setTimeout(function () {
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export()
    })
  }.bind(this), 200)
}

//配送方式弹框隐藏
controller.payhide = function (e) {
  var animation = wx.createAnimation({
    duration: 200,
    timingFunction: "linear",
    delay: 0
  })
  this.animation = animation
  animation.translateY(300).step()
  this.setData({
    animationData: animation.export(),
  })
  setTimeout(function () {
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus2: false
    })
  }.bind(this), 200)
}
//配送时间弹框隐藏
controller.timehide = function (e) {
  var animation = wx.createAnimation({
    duration: 200,
    timingFunction: "linear",
    delay: 0
  })
  this.animation = animation
  animation.translateY(300).step()
  this.setData({
    animationData: animation.export(),
  })
  setTimeout(function () {
    animation.translateY(0).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus1: false
    })
  }.bind(this), 200)
}

controller.onShow  = function(){

};
controller.onHide  = function(){

};
controller.onUnload = function(){

}
Page(controller)